
let context = {
    origin: "",
    serviceUrl: "",
    implUrl: "",
};
self.context = context;
let handle = undefined;

async function initWorker (data) {
    importScripts('systeminit.js');
    await initSystem();

    const serviceModule = await System.import(context.serviceUrl);
    const implModule = await System.import(context.implUrl);
    const serviceCls = serviceModule.default;
    const implCls = implModule.default;
    handle = new serviceCls(new implCls());
    handle.initWorker(self, context, data);
}

function handleMessage (data) {
    return handle.handleWorkMessage(context, data).then((resp) => {
        if (!resp.isResponse) return;
        self.postMessage(resp.resp, resp.tranfers);
    })
}

self.onmessage = function (event) {
    const data = event.data;
    if (data.cmd == 'init') {
        Object.assign(context, data.data.context);
        return initWorker(data.data.data).then(() => {
            self.postMessage({ cmd: data.cmd, seq: data.seq, data: true });
        }).catch((reason) => {
            console.log('init fail::: ', reason);
            self.postMessage({ cmd: data.cmd, seq: data.seq, data: false });
        })
    } else {
        return handleMessage(event.data);
    }
}
